package exercise;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证servlet
 * 1.只要密码是666666，就认为登录成功
 * 2.如果验证成功，则进入管理页面ManageServlet.java，否则进入error.html
 * 3.如果用户直接访问ManageServlet.java(从其他浏览器或者关闭再重启当前浏览器)，直接重定向到error.html
 */
public class LoginCheckServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginCheckServlet 被调用...");

        //1.验证
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (null != username && username.length() != 0
                && null != password && password.length() != 0 && "666666".equals(password)) {
            //转发到管理页面，设置session
            req.getSession().setAttribute("username", username);
            req.getSession().setAttribute("password", password);
            req.getRequestDispatcher("/manage").forward(req, resp);
        } else {
            //转发到登录失败页面
            req.getRequestDispatcher("/exercise/error.html").forward(req, resp);
        }
    }
}
